//
//  HTSearchTruckDriverVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/26.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTSearchTruckDriverVC.h"
#import "HTTruckLicenseView.h"
#import "HTDriverMainVC.h"

/// iOS 9前的框架
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
/// iOS 9的新框架
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
#import <ContactsUI/ContactsUI.h>
#endif

@interface HTSearchTruckDriverVC ()<UITextFieldDelegate,HTTruckLicenseViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *phoneSearchButton;

@property (weak, nonatomic) IBOutlet UIButton *cardSearchButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *cardTextField;
@property (weak, nonatomic) IBOutlet UILabel *inputContactLabel;

@property (nonatomic,strong) NSString *carnumber;

@end

@implementation HTSearchTruckDriverVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索司机";
    self.phoneTextField.delegate = self;
    self.cardTextField.delegate = self;
    self.cardTextField.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(popLicenseView)];
    [self.cardTextField addGestureRecognizer:tap];
    self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.inputContactLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(callContact)];
    [self.inputContactLabel addGestureRecognizer:tap1];
    
}

- (void)callContact{
    [self JudgeAddressBookPower];
}

//点击空白处键盘退出
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.phoneTextField resignFirstResponder];
    
}
- (IBAction)cardSearchAction:(id)sender {
    if (self.carnumber == nil || self.carnumber.length <= 0) {
        [HTShowUtil showMessage:@"请选择车牌号"];
        return;
    }
   [self netLoadDataWithType:@"2" phone:self.carnumber];
}

- (IBAction)phoneSearchAction:(id)sender {
    if (self.phoneTextField.text == nil || self.phoneTextField.text.length <= 0) {
        [HTShowUtil showMessage:@"请输入手机号码"];
        return;
    }
   [self netLoadDataWithType:@"1" phone:self.phoneTextField.text];
}
- (void)didGotCallBackLicense:(NSString *)title{
    self.cardTextField.text = title;
    self.carnumber = title;
}
- (void)popLicenseView{
    [self.phoneTextField resignFirstResponder];
    HTTruckLicenseView *license = [[HTTruckLicenseView alloc]init];
    license.delegate = self;
    [license showView];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneTextField) {
        if (textField.text.length >= 11 && string.length > 0) {
            return NO;
        }else{
            return YES;
        }
    }
    return NO;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == self.cardTextField) {
        [textField resignFirstResponder];
        return NO;
    }else{
        return YES;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark --- 网络请求
- (void)netLoadDataWithType:(NSString *)type phone:(NSString *)phone{
    [self startHud];
    [HTHttpRequestManager requestTruckDriverWithType:type phone:phone success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"查询熟车：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"查询熟车失败"];
            return;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        NSString *ID = [NSString stringWithFormat:@"%@",responseObject[@"id"]];
        HTDriverMainVC *driverMain = [[HTDriverMainVC alloc]init];
        driverMain.ID = ID;
        [self.navigationController pushViewController:driverMain animated:YES];
        
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
         [HTShowUtil showMessage:@"查询熟车失败"];
    }];
}
#pragma mark ---- 调用系统通讯录
- (void)JudgeAddressBookPower { ///获取通讯录权限，调用系统通讯录
    [self CheckAddressBookAuthorization:^(bool isAuthorized , bool isUp_ios_9) { if (isAuthorized) {
        [self callAddressBook:isUp_ios_9];
        
    }else {
        [UIAlertController alertStyleShowInController:self title:@"温馨提示" message:@"请到设置>隐私>通讯录打开本应用的权限设置" alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
            [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        } completion:nil];
    }
    }];
    
}
- (void)callAddressBook:(BOOL)isUp_ios_9 {
    if (isUp_ios_9) {
        CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
        contactPicker.delegate = self;
        contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController:contactPicker animated:YES completion:nil];
    }else {
        ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
        peoplePicker.peoplePickerDelegate = self;
        [self presentViewController:peoplePicker animated:YES completion:nil]; } }

- (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized , bool isUp_ios_9))block {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        CNContactStore * contactStore = [[CNContactStore alloc]init];
        if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * __nullable error) {
                if (error) {
                    NSLog(@"Error: %@", error);
                    
                } else if (!granted){
                    block(NO,YES);
                    
                } else {
                    block(YES,YES);
                    
                }
                
            }]; } else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized){
                block(YES,YES);
                
            } else {
                NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
                
            }
        
    }else {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL); ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        if (authStatus == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_async(dispatch_get_main_queue(), ^{ if (error) {
                    NSLog(@"Error: %@", (__bridge NSError *)error);
                    
                } else if (!granted) {
                    block(NO,NO);
                    
                } else {
                    block(YES,NO);
                    
                }
                    
                });
                
            });
            
        }else if (authStatus == kABAuthorizationStatusAuthorized) {
            block(YES,NO);
            
        }else{
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
            
        }
        
    }
    
}
#pragma mark -- CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    CNPhoneNumber *phoneNumber = (CNPhoneNumber *)contactProperty.value;
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *text1 = [NSString stringWithFormat:@"%@%@",contactProperty.contact.familyName,contactProperty.contact.givenName];
        /// 电话
        NSString *text2 = phoneNumber.stringValue;
        self.phoneTextField.text = text2;
        NSLog(@"联系人：%@, 电话：%@",text1,text2);
    }];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
    CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);
    CFStringRef anFullName = ABRecordCopyCompositeName(person);
    
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *text1 = [NSString stringWithFormat:@"%@",anFullName];
        /// 电话
        NSString *text2 = (__bridge NSString*)value;
        self.phoneTextField.text = text2;
        NSLog(@"联系人：%@, 电话：%@",text1,text2);
    }];
}

@end
